package com.wsoft.bpm.component;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wsoft.bpm.entity.ActProcessMappingEntity;
import com.wsoft.bpm.mapper.BpmActivitiMapper;
import com.wsoft.bpm.service.IActProcessMappingService;
import com.wsoft.bpm.utils.ActivityUtils;
import com.wsoft.core.context.AuthLoginModeContextHolder;
import lombok.extern.log4j.Log4j2;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.wsoft.bpm.constants.BpmConstant.*;

/**
 * 定时任务
 *
 * @Author zhonglj
 * @Date 2024-06-05 17:46
 */
@Log4j2
@Component
public class BpmTask {
    @Resource
    private TaskService taskService;
    @Resource
    private BpmActivitiMapper bpmActivitiMapper;
    @Resource
    private IActProcessMappingService actProcessMappingService;

    /**
     * 定时更新业务映射表数据
     *
     * @param
     * @return void
     * @author zhonglj
     * @date 2025/3/11 16:51
     **/
    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateMappingData() {
        AuthLoginModeContextHolder.not();
        List<ActProcessMappingEntity> mappingEntities = actProcessMappingService.list();
        if (CollUtil.isNotEmpty(mappingEntities)) {
            ArrayList<Long> delIds = CollUtil.newArrayList();
            for (ActProcessMappingEntity mapping : mappingEntities) {
                String id = bpmActivitiMapper.getKeyColumnVal(mapping.getTableName(), "id", mapping.getBusinessKeyColumn(), mapping.getBusinessKey());
                if (id == null) {
                    // 业务数据不存在，需要更新mapping表
                    delIds.add(mapping.getId());
                }
            }

            actProcessMappingService.removeByIds(delIds);
        }

        AuthLoginModeContextHolder.clear();
    }

    /**
     * 定时关闭任务
     *
     * @param
     * @return void
     * @author zhonglj
     * @date 2024-09-24 15:36
     **/
    @Scheduled(cron = "0 0/5 * * * ?")
    public void completeOverdueTasks() {
        AuthLoginModeContextHolder.not();
        List<Task> overDueTasks = taskService.createTaskQuery()
                // 查询所有 dueDate 在当前时间之前的任务
                .taskDueBefore(DateUtil.date())
                // 审批中
                .active()
                .list()
                .stream()
                .filter(task -> {
                    // 跳过动态节点
                    String category = task.getCategory();
                    if (StrUtil.startWith(category, DYNAMIC_NODE)) {
                        return false;
                    }
                    // 跳过正在加签和上级领导审批的节点
                    String assignee = task.getAssignee();
                    if (StrUtil.equals(assignee, DYNAMIC_ASSIGNEE_SIGN)
                            || StrUtil.equals(assignee, DYNAMIC_ASSIGNEE_LEADER)) {
                        return false;
                    }
                    // 跳过会签节点
                    if (ActivityUtils.isMultiTask(task)) {
                        return false;
                    }

                    return true;
                })
                .collect(Collectors.toList());


        for (Task task : overDueTasks) {
            taskService.addComment(task.getId(), task.getProcessInstanceId(), AUTO_COMPLETE_COMMENT);
            taskService.complete(task.getId());
        }

        AuthLoginModeContextHolder.clear();
    }
}
